package antlr.sql;


import org.antlr.v4.runtime.ANTLRInputStream;
import org.antlr.v4.runtime.CommonTokenStream;
import org.antlr.v4.runtime.tree.ParseTree;
import org.antlr.v4.runtime.tree.ParseTreeWalker;

import java.io.IOException;
import java.util.List;

public class SqlParseListener extends SqlBaseListener {

    @Override
    public void enterQuery(SqlParser.QueryContext ctx) {
        String keyword = ctx.children.get(0).getText();  //获取sql规则的第一个元素，为select或者load
//        if("select".equalsIgnoreCase(keyword)){
            execSelect(ctx);   //第一个元素为selece的时候执行select
//        }

    }

    public void execSelect(SqlParser.QueryContext ctx){
        List<ParseTree> children = ctx.children;   //获取该规则树的所有子节点

        String format = "";
        String path = "";
        String tableName = "";

        for (ParseTree c :children) {
            if(c instanceof SqlParser.Select_clauseContext){
                format = c.getText();
            }else if(c instanceof SqlParser.From_clauseContext){
                path = c.getText();
            }else if(c instanceof SqlParser.Column_listContext){
                tableName = c.getText();
            }else if(c instanceof SqlParser.ColumnContext){
                tableName = c.getText();
            }else if(c instanceof SqlParser.AliasContext){
                tableName = c.getText();
            }else if(c instanceof SqlParser.Table_referenceContext){
                tableName = c.getText();
            }
        }
        System.out.println(format);
        System.out.println(path);
        System.out.println(tableName);
        // spark load实现，省略
    }

    public static void main(String[] args) throws IOException {
        String len = "select a from b";
        ANTLRInputStream input = new ANTLRInputStream(len);
        SqlLexer lexer = new SqlLexer(input);
        CommonTokenStream tokens = new CommonTokenStream(lexer);
        SqlParser parser = new SqlParser(tokens);
        SqlParser.QueryContext tree = parser.query();
        SqlParseListener listener = new SqlParseListener();
        ParseTreeWalker.DEFAULT.walk(listener,tree);  //规则树遍历
    }
}